# *-* coding:utf-8 *-*

import urllib, urllib2, cookielib
import Image
import ImageEnhance
import ImageFilter
import sys
import re
from pytesser import *


#调用图形OCR库识别图形为字符，输入图形文件名，输出识别出的验证码
def  getverify1(name):
        # 二值化
    threshold = 140
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)

    #由于都是数字
    #对于识别成字母的 采用该表进行修正
    rep={'O':'0',
        'I':'1','L':'1',
        'Z':'2',
        'S':'8'
        };

    #打开图片
    im = Image.open(name)
    #转化到亮度
    imgry = im.convert('L')
    imgry.save('g'+name)
    #二值化
    out = imgry.point(table,'1')
    out.save('b'+name)
    #识别
    text = image_to_string(out)
    #识别对吗
    text = text.strip()
    text = text.upper();

    for r in rep:
        text = text.replace(r,rep[r])

    #out.save(text+'.jpg')
    print '验证码: ', text
    return text


def login():
    name = 'xxx'
    passwd = 'xxx'
    #使用cookiejar
    cj = cookielib.LWPCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)

    #提取验证码图片写入文件
    ImageUrl = 'http://eip.sc.ctc.com/wps/PA_SCV_Portlet_Login/unauth/randomImgValidateCode.action'
    headers = { 'Accept-Language': 'zh-CN',
                'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                'Host': 'eip.sc.ctc.com',
                'Connection': 'Keep-Alive'
                }
    req = urllib2.Request(ImageUrl, headers=headers,)
    pic = opener.open(req)
    content = pic.read()
    with open('1212.jpg', 'wb') as f:
        f.write(content)
    #调用验证函数获得验证码
    VerNum = getverify1('1212.jpg')

    #使用验证码进行第一次登录，通过登录获取需要第二次登录的cookie
    login_url = 'http://eip.sc.ctc.com/wps/PA_SCV_Portlet_Login/randomCode/preLoginValidate.action'
    post_data = {'userid': name, 'password':passwd, 'validatecode':VerNum}
    login_data = urllib.urlencode(post_data)
    headers = {'Referer': 'http://eip.sc.ctc.com/wps/portal/!ut/p/c4/04_SB8K8xLLM9MSSzPy8xBz9CP0os3hnd0cPE3MfAwMLE3cDA08TJ38_D-dAQwNfQ_2CbEdFAKFB29M!/',
                'Accept-Language': 'zh-CN',
                'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept-Encoding': 'gzip, deflate',
                'Host': 'eip.sc.ctc.com',
                'Connection': 'Keep-Alive',
                'Cache-Control': 'no-cache'
                }
    req = urllib2.Request(login_url, login_data, headers=headers, )
    r = opener.open(req)
    #获取返回内容检查登录是否成功
    ct = r.read()
    flag = re.search(r'"successFlag":(.*?),', ct)
    if flag:
        print 'Login Successful' if flag.group(1)=='true' else 'Login Fail'
    else:
        print 'Login Fail'
        return 'Login Fail'


    #使用验证码和之前获取的COOKIE进行第二次登录
    login_url = 'http://eip.sc.ctc.com/wps/portal/!ut/p/c5/04_SB8K8xLLM9MSSzPy8xBz9QJ_89PTUFP_SEv0I_SizeGd3Rw8Tcx8DAwsTdwMDTxMnfz8P50BDA19DoHykWbwBDuBoQEB3OMhqvPr9EE4pyMixDEhXVAQAIVqhPA!!/dl3/d3/L3dDaXBBQSEhL3dHb0JKdGchLzREMTZSLUlBUUEhIS8zNDE2MjUvbGk!/'
    post_data = {'userid': name, 'password':passwd, 'validatecode':VerNum}
    login_data = urllib.urlencode(post_data)
    headers = {'Referer': 'http://eip.sc.ctc.com/wps/portal/!ut/p/c5/04_SB8K8xLLM9MSSzPy8xBz9QJ_89PTUFP_SEv2CdEVFALCPJr8!/',
                'Accept-Language': 'zh-CN',
                'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept-Encoding': 'gzip, deflate',
                'Host': 'eip.sc.ctc.com',
                'Connection': 'Keep-Alive',
                'Cache-Control': 'no-cache'
                }
    req = urllib2.Request(login_url, login_data, headers=headers, )
    r = opener.open(req)
    #查看cookiejar中保存的cookie
    # for index, cookie in enumerate(cj):
    #     print index, ':', cookie
    #查看跳转后的地址
    reurl = r.geturl()
    return reurl

def getMail():
    name = 'cdjysjtgb'
    passwd = '888888'
    url = 'http://mail7.sc.ctc.com/cdmail/%s.nsf/xIn?OpenAgent' %name
    data = urllib2.urlopen(url).read().decode('gbk', 'ignore')
    pattern = re.compile(r'''style="word-break:break-all" ><p class='red'>(\S*)</p>.*?window.open\('\./\*/(\S*?)'\);.*?<p class='red'>(.*?)</p>.*?<p class='red'>(.*?)</p>''')
    content = pattern.findall(data)
    #mailStr = [ (str(x+1)+'.',m, i,l, '  ') for x, (i, l, m) in enumerate(content)]

    #mailStr = [y for x in d for y in x]
    
    return content

def getMailCont(offset):
    name = 'xxx'
    passwd = 'xxx'
    r_url = login()
    try:
        mHead ='http://mail7.sc.ctc.com/cdmail/%s.nsf/xIn/' % name 
        mUrl = mHead + offset
        mCont = urllib2.urlopen(mUrl).read().decode('gbk', 'ignore')
        return mCont
    except:
        return 'No data'
    
    
    
    
def main():
    r_url = login()
    mailst = getMail()
    return mailst

if __name__ == '__main__':
    a = main()